<?php
/*
+--------------------------------------------------------------------------
|   WeCenter [#RELEASE_VERSION#]
|   ========================================
|   by WeCenter Software
|   © 2011 - 2014 WeCenter. All Rights Reserved
|   http://www.wecenter.com
|   ========================================
|   Support: WeCenter@qq.com
|
+---------------------------------------------------------------------------
*/
/**
 *商品管理
 *
 */

if (!defined('IN_ANWSION')) {
    die;
}

class  goods_class extends AWS_MODEL
{


    /**
     * 更新商品表
     * @param $update_data  array
     * @param $gid
     * @return int
     * @throws Zend_Exception
     */

    public function update_goods_fields($update_data, $gid)
    {

        if (!$update_data OR !$gid) {
            return false;
        }

        $update_data['update_time'] = time();
        return $this->update('goods', $update_data, 'goods_id = ' . intval($gid));

    }

    /**
     * 插入商品基础数据
     * @param $cat_id
     * @param $goods_name
     * @param $goods_sn
     * @param $keywords
     * @param $is_new
     * @param $is_best
     * @param $is_hot
     * @param $is_promote
     */

    public function insert_goods($cat_id, $goods_name, $goods_sn, $keywords, $is_new = 0, $is_best = 0, $is_hot = 0, $is_promote = 0)
    {

        if (!$goods_name OR !$cat_id) {
            return false;
        }

        $goods_id = $this->insert('goods', array(
            'cat_id' => $cat_id,
            'goods_name' => $goods_name,
            'goods_sn' => $goods_sn,
            'keywords' => trim($keywords),
            'is_new' => $is_new,
            'is_best' => $is_best,
            'is_hot' => $is_hot,
            'is_promote' => $is_promote,
            'add_time' => time()
        ));

        return $goods_id;

    }


    /**
     * 通过 GID 获取商品信息
     *
     * $cache_result 为是否缓存结果
     *
     * @param string
     * @param boolean
     * @param boolean
     * @return array
     */
    public function get_goods_info_by_gid($gid, $cache_result = true)
    {
        if (!$gid) {
            return false;
        }

        if ($gid == -1) {
            return array(
                'goods_id' => -1,
                'goods_name' => AWS_APP::lang()->_t('[已注销]'),
            );
        }

        if ($cache_result) {
            static $goods_info;

            if ($goods_info[$gid]) {
                return $goods_info[$gid];
            }
        }

        if (!$goods_info = $this->fetch_row('goods', 'goods_id = ' . intval($gid))) {
            return false;
        }

        $goods_info[$gid] = $goods_info;


        return $goods_info;
    }
    /**
     * 通过 GID 获取商品列表
     *
     * $cache_result 为是否缓存结果
     *
     * @param array
     * @return array
     */
    public function get_goods_info_by_gids($gids)
    {
        if (!$gids) {
            return false;
        }

        if (!$goods_info = $this->query_all("SELECT DISTINCT goods_id,goods_sn,goods_name,goods_brief,market_price,shop_price,promote_price,cover,tb_url,jd_url FROM ".$this->get_table('goods'). " WHERE goods_id IN(".implode(',',$gids).")")) {
            return false;
        }

        return $goods_info;
    }

    /**
     * 检查商品名是否已经存在
     *
     * @param string
     * @return boolean
     */
    public function check_goodsname($goods_name)
    {
        $goods_name = trim($goods_name);

        return $this->fetch_one('goods', 'goods_id', "goods_name = '" . $this->quote($goods_name) . "'");
    }


    /**
     * 检查商品编码名是否已经存在
     *
     * @param string
     * @return boolean
     */
    public function check_goodssn($goods_sn)
    {
        $goods_sn = trim($goods_sn);

        return $this->fetch_one('goods', 'goods_id', "goods_sn = '" . $this->quote($goods_sn) . "'");
    }

    /**
     * 获取商品封面图地址
     *
     * 举个例子：$gid=12345，那么图片路径很可能(根据您部署的上传文件夹而定)会被存储为/uploads/000/01/23/45_goods_min.jpg
     *
     * @param  int
     * @param  string
     * @param  int
     * @return string
     */
    public function get_goods_cover($gid, $size = 'min', $return_type = 0)
    {
        $size = in_array($size, array(
            'max',
            'mid',
            'min',
            '50',
            '150',
            'big',
            'middle',
            'small'
        )) ? $size : 'real';

        $gid = abs(intval($gid));
        $gid = sprintf('%\'09d', $gid);
        $dir1 = substr($gid, 0, 3);
        $dir2 = substr($gid, 3, 2);
        $dir3 = substr($gid, 5, 2);

        if ($return_type == 1) {
            return $dir1 . '/' . $dir2 . '/' . $dir3 . '/';
        }

        if ($return_type == 2) {
            return substr($gid, -2) . '_goods_style_' . $size . '.jpg';
        }

        return $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($gid, -2) . '_goods_' . $size . '.jpg';
    }

    /**
     * @param $item_type
     * @param $file_name
     * @param $attach_access_key
     * @param $add_time
     * @param $file_location
     * @param bool $is_image
     * @return int
     */
    public function add_cover($item_id,$item_type, $file_name, $attach_access_key, $add_time, $file_location, $is_image = false)
    {
        if ($is_image)
        {
            $is_image = 1;
        }

        return $this->insert('attach', array(
            'file_name' => htmlspecialchars($file_name),
            'access_key' => $attach_access_key,
            'add_time' => $add_time,
            'file_location' => htmlspecialchars($file_location),
            'is_image' => $is_image,
            'item_type' => $item_type,
            'item_id' => $item_id
        ));
    }
    /**
     * @param $id
     * @return bool
     *
     */
    public function get_cover_by_id($id)
    {
        if ($attach = $this->fetch_row('attach', 'id = ' . intval($id)))
        {
            $data = $this->parse_attach_data(array($attach), $attach['item_type'], 'square',$attach['item_id']);

            return $data[$id];
        }

        return false;
    }


    public function parse_attach_data($attach, $item_type, $size = null, $gid)
    {
        if (!$attach OR !$item_type OR !$gid) {
            return false;
        }

        foreach ($attach as $key => $data) {
            if (in_array($item_type, array(
                'question',
                'weibo_msg'
            ))) {
                $item_type = 'questions';
            }

            // Fix 2.0 attach time zone bug
            $date_dir = $this->get_goods_cover($gid, 'min', 1); // gmdate('Ymd', $data['add_time']);
            if (!file_exists(get_setting('upload_dir') . '/' . $item_type . '/' . $date_dir  . $data['file_location'])) {
                $date_dir = gmdate('Ymd', ($data['add_time'] + 86400));
            }

            $attach_url = get_setting('upload_url') . '/' . $item_type . '/' . $date_dir . '/';

            $attach_path = get_setting('upload_dir') . '/' . $item_type . '/' . $date_dir . '/';

            $attach_list[$data['id']] = array(
                'id' => $data['id'],
                'is_image' => $data['is_image'],
                'file_name' => $data['file_name'],
                'access_key' => $data['access_key'],
                'file_location' => $data['file_location'],
                'attachment' => $attach_url . $data['file_location'],
                'path' => $attach_path . $data['file_location']
            );

            if ($data['is_image'] == 1 AND $size) {
                $attach_list[$data['id']]['thumb'] = $attach_url . AWS_APP::config()->get('image')->attachment_thumbnail[$size]['w'] . 'x' . AWS_APP::config()->get('image')->attachment_thumbnail[$size]['h'] . '_' . $data['file_location'];
            }
        }

        return $attach_list;
    }

    /**
     * 获取封面图片
     * @param $item_type
     * @param $item_id
     * @param string $size
     * @return bool|mixed
     */

    public function get_cover($item_type, $item_id, $size = 'square')
    {
        if (!is_digits($item_id)) {
            return false;
        }

        $attach = $this->fetch_all('attach', "item_type = '" . $this->quote($item_type) . "' AND item_id = " . $item_id, "is_image DESC, id ASC");

        return $this->parse_attach_data($attach, $item_type, $size, $item_id);
    }


    /**
     * @param $where
     * @param int $limit
     * @return array|bool
     * @throws Exception
     * 获取首页的商品信息
     */
    public  function  get_home_goods_list($where,$limit = 4)
    {
        if(!$where){
            return false;
        }

        if ($goods = $this->query_all("SELECT DISTINCT goods_id,cat_id,goods_name,keywords,goods_brief,market_price,shop_price,promote_price,give_integral,tb_url,jd_url,cover FROM " . $this->get_table('goods') . " WHERE  ".implode(' AND ', $where). "  ORDER BY sort_order ASC", $limit)){

            return $goods;
        }
        return false;


    }


    /**
     * 更新商品表
     * @param $update_data  array
     * @param $gsid
     * @return int
     * @throws Zend_Exception
     */

    public function update_goods_style_fields($update_data, $gsid)
    {

        if (!$update_data OR !$gsid) {
            return false;
        }
        $update_data['update_time'] = time();
        return $this->update('goods_style', $update_data, 'id = ' . intval($gsid));

    }

    /**
     * @param $insert_data
     * @param $gsid
     * @return bool|int
     * 插入规格表
     */

    public function insert_goods_style_fields($insert_data)
    {

        if (!$insert_data) {
            return false;
        }
        $update_data['add_time'] = time();

        return $this->insert('goods_style', $insert_data);

    }

    /**
     * @param $gid
     * @param int $limit
     * @return array
     * @throws Exception
     *
     */
    public  function get_goods_style_list($gid,$limit=20)
    {


        $where[]=" state = 1";
        $where[]=" gid = ".intval($gid);

        if ($goods = $this->query_all("SELECT DISTINCT * FROM " . $this->get_table('goods_style') . " WHERE  ".implode(' AND ', $where). "  ORDER BY  add_time ASC", $limit)){

            return $goods;
        }
        return false;
    }

    /**
     * @param $gid
     * @param int $limit
     * @return array|bool
     * @throws Exception
     * 获取型号
     */
    public  function get_goods_model_list($gid,$limit=20)
    {


        $where[]=" state = 1";
        $where[]=" gid = ".intval($gid);

        if ($goods = $this->query_all("SELECT DISTINCT * FROM " . $this->get_table('goods_style') . " WHERE  ".implode(' AND ', $where). " GROUP BY goods_model ORDER BY  add_time ASC ", $limit)){

            return $goods;
        }
        return false;
    }

    /**
     * @param $cols
     * @param $where
     * @param $order
     * @return array
     * @throws Exception
     *
     */
    public  function  get_goods_list_page($cols,$where,$order){

        $list = $this->fetch_page_by_cols('goods', $cols, implode(' AND ', $where), $order, $_GET['page'], $this->per_page);

        foreach ($list as $key=>$item){
            $goods_style  = $this->query_all("SELECT DISTINCT gid,goods_color,goods_color_pic  FROM " . $this->get_table('goods_style') . " WHERE  gid=".$item['goods_id']. " GROUP BY goods_color",2);
            $list[$key]['goods_style'] =$goods_style;
        }
        $total_rows = $this->found_rows();

        return array(
            'list'=>$list,
            'total_rows'=>$total_rows
        );
    }

    /**
     * 处理首页数据
     */
    public  function  get_home_data(){


        $home_data = (array)AWS_APP::config()->get('home_data_v1');

        $home  = $home_data[0];

        foreach ($home['goods_category'] AS $key=>$val){

            $where[]=" goods_id IN(".$val['goods_ids'].")";
            $goods  = $this->get_home_goods_list($where);
            $home['goods_category'][$key]['goods'] = $goods;
        }

        foreach ($home['goods_list'] AS $key=>$val){
            $where2[]=" goods_id IN(".$val['goods_ids'].")";
            $goods  = $this->get_home_goods_list($where2);
            $home['goods_list'][$key]['goods'] = $goods;
            
            array_splice($where2, 0, count($where2));

        }
        return $home;
    }
    /**
     * 处理wap首页数据
     */
    public  function  get_wap_home_data()
    {

        $home_data = (array)AWS_APP::config()->get('home_data_v1');

        $home  = $home_data[1];
        if(!$home_data){
            return false;
        }
        foreach ($home['goods_list'] AS $key=>$val){
            $where2[]=" goods_id IN(".$val['goods_ids'].")";
            $goods  = $this->get_home_goods_list($where2);
            $home['goods_list'][$key]['goods'] = $goods;

            array_splice($where2, 0, count($where2));

        }
        return $home;
    }



}